# -*- coding: utf-8 -*-
"""
@desc: 数据填报部分
"""

from flask import Blueprint, request, current_app
from flask.globals import current_app
from flask_login import login_required, current_user
import os
import time
from app import db
from models import File, Record, Message, Subject
import json
import hashlib

upload = Blueprint('upload', __name__)

@upload.route('/upload/<point_id>', methods=['POST'])
@login_required
def upload_point_file(point_id):
    f = request.files.get('file') # 获得文件
    sub = request.form.get('subject')
    # print("上传的文件名：%s, 学科名为：%s" % (f.filename, sub))
    current_app.logger.info("上传的文件名：%s, 学科名为：%s" % (f.filename, sub))
    if f: # 如果接收到文件
        if point_id.startswith('D'):
            file_path = './data/fill_data/university/'
        elif point_id.startswith('X'):
            file_path = './data/fill_data/subject/' + str(sub)+'/'
        else:
            return json.dumps({'status_code':404, "reason":"文件名称或者格式有问题"}, ensure_ascii=False)
        hash_filename = hashlib.md5(f.read()).hexdigest()+'.xlsx' #
        save_path = os.path.join(file_path, hash_filename) # 上传时间+文件名
        print(save_path) # 打印文件保存路径
        if os.path.exists(save_path):
            os.remove(save_path)
        f.seek(0)
        f.save(save_path)
        try:
            if point_id.startswith('D'):
                # 如果file存在，则直接删除
                File.query.filter_by(point = point_id).delete()
                db.session.commit()
            elif point_id.startswith('X'):
                File.query.filter_by(file_type=sub, point=point_id).delete()
                db.session.commit()
            upload_time = get_dateformat()
            new_file = File(point=point_id,
                            name=f.filename, # 文件名，文件名不变
                            path=save_path,
                            file_type=sub,
                            status='已上传',
                            user_id=current_user.id,
                            upload_time=upload_time)
            db.session.add(new_file)
            db.session.commit()
            # 增加record:
            record = Record(point_id = point_id,
                            file_name= f.filename,
                            record_type=sub,
                            user_id=current_user.id,
                            upload_time=upload_time,
                            op_type="上传")
            db.session.add(record)
            db.session.commit()

        except Exception as e:
            print(e)
            db.session.rollback()
        return json.dumps({'status_code':200, 'id':point_id, 'state':'已上传'}, ensure_ascii=False) # 传一个json，去更新状态。
    else: # 没有收到文件
        return json.dumps({'status_code':404, 'info':'上传文件失败'}, ensure_ascii=False) # 提示上传文件错误。

subject = Subject.query.all()
subject_names = [s.name for s in subject]

# 返回当前格式化时间状态
# def get_dateformat():
#     now = int(time.time())
#     timeArray = time.localtime(now)
#     upload_time = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
#     return upload_time

import pytz
import datetime
tz = pytz.timezone('Asia/Shanghai')

def get_dateformat():
    now = int(time.time())
    result = datetime.datetime.fromtimestamp(now, tz).strftime("%Y-%m-%d %H:%M:%S")
    return result

@upload.route('/upload/data-list', methods=['POST'])
@login_required
def upload_data_list():
    """
    一键上传文件夹
    :return:
    """
    f = request.files.get('file')      
    name = request.form.get('path')
    current_app.logger.info(name)
    if name.count('/') == 1: # 只有2层目录
        x = name.split('/')
        if x[0] not in subject_names:
            if x[1].startswith('D'): # ['test', 'D020101.xlsx']
                if str(x[1]).startswith('D020303_本科'):
                    point = 'D020303'
                elif str(x[1]).startswith('D020303_认证'):
                    point = 'D02030X'
                else:
                    point = x[1][:7]
                File.query.filter_by(point=point).delete() # 删除原来的
                db.session.commit()
                upload_time = get_dateformat() # 获取当前时间

                save_dir = './data/fill_data/university/'
                if not os.path.exists(save_dir):
                    os.makedirs(save_dir)
                hash_filename = hashlib.md5(f.read()).hexdigest() +'.xlsx'
                save_path = save_dir + hash_filename
                f.seek(0)
                f.save(save_path)
                # 增加file记录
                new_File = File(point = point,
                                name=x[1],
                                path=save_path,
                                file_type='大学',
                                status='已上传',
                                user_id=current_user.id,
                                upload_time=upload_time)
                db.session.add(new_File)
                db.session.commit()

                record = Record(point_id=point,
                                file_name=x[1],
                                record_type="大学",
                                user_id=current_user.id,
                                upload_time=upload_time,
                                op_type="上传")
                db.session.add(record)
                db.session.commit()
                return json.dumps({"info": "批量文件上传完成"})
            else:
                return json.dumps({"info":"未能识别文件所属的学科名称"})
        else: # 以学科名命名的 ["哲学", "X010101.xlsx"]
            File.query.filter_by(point=x[1][:7], file_type=x[0]).delete()  # 删除原来的
            db.session.commit()
            upload_time = get_dateformat()
            save_dir = './data/fill_data/subject/' + str(x[0]) + '/'
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            hash_filename = hashlib.md5(f.read()).hexdigest() + '.xlsx'
            save_path = save_dir + hash_filename
            f.seek(0)
            f.save(save_path)
            # 插入数据库操作
            new_File = File(point=x[1][:7],
                            name=str(x[1]),
                            path=save_path,
                            file_type=x[0],
                            status='已上传',
                            user_id=current_user.id,
                            upload_time=upload_time)
            db.session.add(new_File)
            db.session.commit()

            record = Record(point_id=x[1][:7],
                            file_name=str(x[1]),
                            record_type=x[0],
                            user_id=current_user.id,
                            upload_time=upload_time,
                            op_type="上传")
            db.session.add(record)
            db.session.commit()
            return json.dumps({"info": "批量文件上传完成"})

    elif name.count('/') == 2: # 只有3层目录
        # 默认他会保存的很好
        x = name.split('/') # ['', 物理学, X00001.xlsx]
        sub = x[1]
        upload_time = get_dateformat()
        if sub not in subject_names:
            return json.dumps({"info":"未能正确识别待上传的文件"}, ensure_ascii=False)
        f_name = x[2]
        save_dir = './data/fill_data/subject/' + str(sub) + '/'
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        hash_filename = hashlib.md5(f.read()).hexdigest() + '.xlsx'
        save_path = save_dir + hash_filename
        f.seek(0)
        f.save(save_path)
        # File更新
        File.query.filter_by(point=f_name[:7], file_type=sub).delete()  # 删除原来的
        db.session.commit()
        new_File = File(point=f_name[:7],
                        name= f_name,
                        path=save_path,
                        file_type=sub,
                        status='已上传',
                        user_id = current_user.id,
                        upload_time=upload_time)
        db.session.add(new_File)
        db.session.commit()

        # Record更新
        record = Record(point_id=f_name[:7],
                        file_name=f_name,
                        record_type=sub,
                        user_id=current_user.id,
                        upload_time=upload_time,
                        op_type="上传")
        db.session.add(record)
        db.session.commit()
        return json.dumps({"info":"批量文件上传完成"})
    else:
        return json.dumps({"info":"未能正确识别文件的归属学科或单位"})